package com.zh.juc.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @Author: zhanghuan
 * @date: 2022/10/19 19:32
 * @description: create it
 * 引用类型原子类
 * - AtomicReference
 * - AtomicStampedReference 解决ABA问题，解决修改过几次问题
 * - AtomicMarkableReference 解决是否修改问题
 * <p>
 * 对象属性修改原子类
 * - AtomicIntegerFieldUpdater
 * - AtomicLongFieldUpdater
 * - AtomicReferenceFieldUpdater
 */
public class AtomicMarkableReferenceDemo {

    static AtomicMarkableReference markableReference = new AtomicMarkableReference(100, false);

    public static void main(String[] args) {
        new Thread(() -> {
            boolean marked = markableReference.isMarked();
            System.out.println(Thread.currentThread().getName() + "\t" + "默认标识：" + marked);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            markableReference.compareAndSet(100, 2022, marked, !marked);
        }, "t1").start();

        new Thread(() -> {
            boolean marked = markableReference.isMarked();
            System.out.println(Thread.currentThread().getName() + "\t" + "默认标识：" + marked);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = markableReference.compareAndSet(100, 2023, marked, !marked);
            System.out.println(Thread.currentThread().getName() + "\t" + "CAS结果：" + marked);
            System.out.println(Thread.currentThread().getName() + "\t" + markableReference.isMarked());
            System.out.println(Thread.currentThread().getName() + "\t" + markableReference.getReference());

        }, "t2").start();


    }
}
